package cn.codecang.mall.service.impl;

import cn.codecang.mall.common.consts.ErrorCode;
import cn.codecang.mall.common.response.Result;
import cn.codecang.mall.common.utils.JWTUtil;
import cn.codecang.mall.vo.user.LoginReqVo;
import cn.codecang.mall.vo.user.LoginRespVo;
import cn.codecang.mall.entity.User;
import cn.codecang.mall.dao.IUserRepository;
import cn.codecang.mall.service.IUserService;

import org.jetbrains.annotations.NotNull;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * UserServiceImpl
 *
 * @author xiaoluo
 * @date 2023/6/2 16:02
 */
@Service
public class UserServiceImpl implements IUserService {

    private final IUserRepository userRepository;

    public UserServiceImpl(IUserRepository userRepository) {
        Assert.notNull(userRepository, "IUserRepository must not be null");
        this.userRepository = userRepository;
    }

    /**
     * 登录
     *
     * @param request 请求
     * @return {@link Result}<{@link LoginRespVo}>
     */
    @Override
    public Result<LoginRespVo> login(@NotNull LoginReqVo request) {
        User user = userRepository.findByUsernameAndPassword(request.getUsername(), request.getPassword());
        if (user == null) {
            return Result.error(ErrorCode.INVALID_PARAMETER);
        }
        // 生成jwt
        Map<String, String> payload = new HashMap<>();
        payload.put("id", "1");
        payload.put("username", request.getUsername());
        String token = JWTUtil.generateToken(payload);
        LoginRespVo response = new LoginRespVo();
        response.setToken(token);
        return Result.success(response);
    }

    @Override
    @Cacheable(value = "myCache", key = "#id")
    public User getById(Long id) {
        Optional<User> res = userRepository.findById(id);
        return res.get();
    }
}
